//
//  TLScrollPlayViewController.m
//  TLAVPlayerDemo
//
//  Created by Tianlong on 2017/7/8.
//  Copyright © 2017年 Tianlong. All rights reserved.
//

#import "TLScrollPlayViewController.h"
#import "Masonry.h"
#import "TLScrollPlayCell.h"
#import "TLScrollPlayModel.h"
#import "TLAVPlayerLayer.h"

@interface TLScrollPlayViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , weak) UITableView *tableView;
@property (nonatomic , strong) NSMutableArray *dataM;

/**
 顶部辅助线
 */
@property (nonatomic , weak) UIView *topLine;

/**
 底部辅助线
 */
@property (nonatomic , weak) UIView *bottomLine;

/**
 记录上一次滚动的位置,用来判断滚动方向
 */
@property (nonatomic , assign) CGFloat lastOffsetY;

/** 
 正在播放的cell所在的索引 
 */
@property (nonatomic , strong) NSIndexPath *playIndexPath;

/**
 正在播放的cell
 */
@property (nonatomic , strong) TLScrollPlayCell *playCell;

/** 
 模拟首次拉取数据，播放第一行cell
 */
@property (nonatomic , assign) BOOL firstLoad;

/**
 初始的offsetY
 */
@property (assign, nonatomic) CGFloat initOffsetY;

/**
 首次设置initOffsetY的标记
 */
@property (nonatomic, assign) BOOL firstInitOffsetY;

@end

@implementation TLScrollPlayViewController

static NSString *cellId = @"TLScrollPlayCell";


-(NSMutableArray *)dataM{
    if (_dataM == nil) {
        _dataM = [NSMutableArray array];
    }
    return _dataM;
}

#pragma mark - 控制器生命周期方法
-(void)loadView{
    [super loadView];
    
    [self setupTable];
    self.playIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.firstLoad = YES;
    self.firstInitOffsetY = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //设置辅助线
    [self setupLine];
    
    NSMutableArray *urlM = [NSMutableArray arrayWithObjects:
                    @"https://o79mx21qy.qnssl.com/lmr-cTeyUxoZqNX8nH4_174k_7Px",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",
                            
                    @"http://7xlv47.com1.z0.glb.clouddn.com/xxx004.m3u8",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/Fuuh5VOKFGRBzlKubIH471oL-3lu",

                    @"https://cdn-video-sns.piyingke.com/Fr2Ghmt6KqPzIer3SYpB8bmQ-Z4p",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FhaNxVDg6zkP_hi5d7hrRU-wMbsF",

                    @"https://cdn-video-sns.piyingke.com/FpnFI2P91Glc4AjTI-9HkvP_wvdX",

                    @"https://cdn-video-sns.piyingke.com/FpzFpthVyLovOE2Nd7uBiXamyCE5",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fl-8OdYHjCRCSN1v87NLnXkEFdei",

                    @"",

                    @"https://cdn-video-sns.piyingke.com/351e20fe-9973-4c49-a7ee-9e9686138322_-1_-1_.mp4",

                    @"",

                    @"https://cdn-video-sns.piyingke.com/FqIiyX0V4XKg2RUOkU1K6FDC0L4Q",
                            
                    @"",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"",

                    @"https://cdn-video-sns.piyingke.com/Fuuh5VOKFGRBzlKubIH471oL-3lu",

                    @"https://cdn-video-sns.piyingke.com/Fr2Ghmt6KqPzIer3SYpB8bmQ-Z4p",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FhaNxVDg6zkP_hi5d7hrRU-wMbsF",

                    @"https://cdn-video-sns.piyingke.com/FpnFI2P91Glc4AjTI-9HkvP_wvdX",

                    @"https://cdn-video-sns.piyingke.com/FpzFpthVyLovOE2Nd7uBiXamyCE5",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fl-8OdYHjCRCSN1v87NLnXkEFdei",

                    @"https://cdn-video-sns.piyingke.com/FuSZHwPHDye_1pLtFFr6hxf2yDfU",

                    @"https://cdn-video-sns.piyingke.com/351e20fe-9973-4c49-a7ee-9e9686138322_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/FjKCG5OQ7iPZay8sKRLkAva6R8vW",

                    @"https://cdn-video-sns.piyingke.com/FqIiyX0V4XKg2RUOkU1K6FDC0L4Q",
                            
                    @"https://o79mx21qy.qnssl.com/lmr-cTeyUxoZqNX8nH4_174k_7Px",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/Fuuh5VOKFGRBzlKubIH471oL-3lu",

                    @"https://cdn-video-sns.piyingke.com/Fr2Ghmt6KqPzIer3SYpB8bmQ-Z4p",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FhaNxVDg6zkP_hi5d7hrRU-wMbsF",

                    @"https://cdn-video-sns.piyingke.com/FpnFI2P91Glc4AjTI-9HkvP_wvdX",

                    @"https://cdn-video-sns.piyingke.com/FpzFpthVyLovOE2Nd7uBiXamyCE5",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fl-8OdYHjCRCSN1v87NLnXkEFdei",

                    @"https://cdn-video-sns.piyingke.com/FuSZHwPHDye_1pLtFFr6hxf2yDfU",

                    @"https://cdn-video-sns.piyingke.com/351e20fe-9973-4c49-a7ee-9e9686138322_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/FjKCG5OQ7iPZay8sKRLkAva6R8vW",

                    @"https://cdn-video-sns.piyingke.com/FqIiyX0V4XKg2RUOkU1K6FDC0L4Q",
                            
                    @"https://o79mx21qy.qnssl.com/lmr-cTeyUxoZqNX8nH4_174k_7Px",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/1fc78e0a-78a0-432c-b8f0-d0807dd9b9ad_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/Fuuh5VOKFGRBzlKubIH471oL-3lu",

                    @"https://cdn-video-sns.piyingke.com/Fr2Ghmt6KqPzIer3SYpB8bmQ-Z4p",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FqDd9Q5VU6Kgk_YnT3nmQ5GzRw20",

                    @"https://cdn-video-sns.piyingke.com/FhaNxVDg6zkP_hi5d7hrRU-wMbsF",

                    @"https://cdn-video-sns.piyingke.com/FpnFI2P91Glc4AjTI-9HkvP_wvdX",

                    @"https://cdn-video-sns.piyingke.com/FpzFpthVyLovOE2Nd7uBiXamyCE5",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fq9AC4R3QJRn3RsromDMQcSmWujl",

                    @"https://cdn-video-sns.piyingke.com/Fl-8OdYHjCRCSN1v87NLnXkEFdei",

                    @"https://cdn-video-sns.piyingke.com/FuSZHwPHDye_1pLtFFr6hxf2yDfU",

                    @"https://cdn-video-sns.piyingke.com/351e20fe-9973-4c49-a7ee-9e9686138322_-1_-1_.mp4",

                    @"https://cdn-video-sns.piyingke.com/FjKCG5OQ7iPZay8sKRLkAva6R8vW",

                    @"https://cdn-video-sns.piyingke.com/FqIiyX0V4XKg2RUOkU1K6FDC0L4Q",
                    nil];
    
    for (NSString *url in urlM) {
        TLScrollPlayModel *model = [[TLScrollPlayModel alloc] init];
        model.videoURL = url;
        TLAVPlayer *player = [[TLAVPlayer alloc] init];
        player.beginTime = 0;
        player.autoPlay = NO;
        player.showBackBtnInSmallScreen = NO;
        player.coverView.hidden = NO;
        player.videoUrl = url;
        model.player = player;
        [self.dataM addObject:model];
    }
    
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - table
-(void)setupTable{
    UITableView *table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView = table;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setDataSource:self];
    [self.tableView setDelegate:self];
    [self.view addSubview:self.tableView];
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark - 初始化各种视图
-(void)setupLine{
    /** 创建辅助线 */
    UIView *topline = [[UIView alloc] init];
    self.topLine = topline;
    self.topLine.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.topLine];
    
    [self.topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.top.offset(64);
        make.height.offset(1);
    }];
    
    UIView *bottomLine = [[UIView alloc] init];
    self.bottomLine = bottomLine;
    self.bottomLine.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.bottomLine];
    
    [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
}

#pragma mark - tableview 代理、数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataM.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TLScrollPlayModel *playModel = nil;
    if (indexPath.row < self.dataM.count) {
        playModel = self.dataM[indexPath.row];
        playModel.index = indexPath.row;
    }
    
    TLScrollPlayCell *cell = [TLScrollPlayCell cellWithTableView:tableView model:playModel cellStyle:TLTableViewCellStyleDefault];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:30];
    cell.playModel = playModel;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}



#pragma mark - 滚动播放：定位被播放的 indexPath
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.firstInitOffsetY) {
        self.initOffsetY = scrollView.contentOffset.y;
        self.firstInitOffsetY = NO;
    }
    [self caculatePlayIndexPath];
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self caculatePlayIndexPath];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self caculatePlayIndexPath];
}

/**
 计算播放的索引
 */
-(void)caculatePlayIndexPath{
    
    /***** 核心处理：哪个cell播放拿哪个cell上的player来作比较 **/
    if (self.tableView.contentOffset.y <= self.initOffsetY) {
        if (self.firstLoad) {
            if (self.playIndexPath.row == 0) {
                [self playWithIndexPath:self.playIndexPath];
            }
            self.firstLoad = NO;
        }
        else{
            if (self.playIndexPath.row == 0) {
                return;
            }
            [self stopPlayWithIndexPath:self.playIndexPath];
            self.playIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [self playWithIndexPath:self.playIndexPath];
        }
    }
    else{
        //获取当前正在播放的cell
        TLScrollPlayCell *playCell = [self getIndextCell:self.playIndexPath];
        //cell先将播放器的 frame 转换到 table 上
        //CGRect playerInTableF = [playCell convertRect:playCell.playModel.player.frame toView:self.tableView];
        CGRect playerInTableF = [playCell convertRect:playCell.middView.frame toView:self.tableView];
        //table再将播放器的 frame 转换到 view 上
        CGRect playerInViewF = [self.tableView convertRect:playerInTableF toView:[self.tableView superview]];
        //player的上半部分
        CGRect halfUp = CGRectMake(playerInViewF.origin.x, playerInViewF.origin.y, playerInViewF.size.width, playerInViewF.size.height*0.5);
        //player的下半部分
        CGRect halfDown = CGRectMake(playerInViewF.origin.x, playerInViewF.origin.y+playerInViewF.size.height*0.5, playerInViewF.size.width, playerInViewF.size.height*0.5);
        
        if(self.tableView.contentOffset.y+fabs(self.tableView.contentInset.top) > fabs(self.tableView.contentInset.top)-fabs(self.tableView.contentInset.top)){
            
            //1.上推视图，参考顶部辅助线。正在播放的视频的player 压住了顶部的cell
            if (CGRectContainsPoint(playerInViewF, self.topLine.center) &&
                !CGRectContainsPoint(playerInViewF, self.bottomLine.center)){
                
                NSInteger index = 0;
                if (self.tableView.contentOffset.y >= self.lastOffsetY){
                    
                    if (CGRectContainsPoint(halfUp, self.topLine.center)) {//视频区域的上半部分
                        
                    }
                    else if(CGRectContainsPoint(halfDown, self.topLine.center)){//视频区域的下半部分
                        index = self.playIndexPath.row+1 >= 0 ? (self.playIndexPath.row+1) : 0;
                        [self stopPlayWithIndexPath:self.playIndexPath];
                        self.playIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
                        [self playWithIndexPath:self.playIndexPath];
                    }
                }
            }
            
            //2.下拉视图时，参考底部辅助线。正在播放的视频的player 压住了底部的cell
            else if (CGRectContainsPoint(playerInViewF, self.bottomLine.center) &&
                     !CGRectContainsPoint(playerInViewF, self.topLine.center)){
                
                NSInteger index = 0;
                if (CGRectContainsPoint(halfUp, self.bottomLine.center)) {//视频区域的上半部分
                    index = self.playIndexPath.row-1 >= 0 ? (self.playIndexPath.row-1) : 0;
                    [self stopPlayWithIndexPath:self.playIndexPath];
                    self.playIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
                    [self playWithIndexPath:self.playIndexPath];
                }
                else if(CGRectContainsPoint(halfDown, self.bottomLine.center)){//视频区域的下半部分
                    
                }
            }
            
            //3.正在播放的视频的player 谁也没压住，就不做处理，继续播放当前的
            else{
                CGFloat playerCenterY = playerInViewF.origin.y+playerInViewF.size.height*0.5;
                if (playerCenterY < self.bottomLine.center.y && playerCenterY > self.topLine.center.y) {
                    
                }
                else{
                    [self stopPlayWithIndexPath:self.playIndexPath];
                    [self caculateIndexPathDependScreenCenterY];
                    NSLog(@"如果来到这里则正在快速滚动");
                }
            }
        }
    }
    self.lastOffsetY = self.tableView.contentOffset.y;
}

#pragma mark - 通过中心点来计算播放哪一个
-(CGFloat)caculateIndexPathDependScreenCenterY{
    
    //将屏幕中心点的左边转到view上
    UIWindow *win = [UIApplication sharedApplication].keyWindow;
    CGPoint screenInViewF = [[UIApplication sharedApplication].keyWindow convertPoint:win.center toView:self.tableView.superview];
    CGFloat screenInViewCenterY = screenInViewF.y;
    
    //将可见cell的中心点全部转到view上
    CGFloat minDiff = MAXFLOAT;//两个中心点的差值,如果差值余越小则该播放这个cell
    TLScrollPlayCell *playCell = nil;
    for (TLScrollPlayCell *cell in self.tableView.visibleCells) {
        //CGRect playerInTableF = [cell convertRect:cell.playModel.player.frame toView:self.tableView];
        CGRect playerInTableF = [cell convertRect:cell.middView.frame toView:self.tableView];
        CGRect playerInViewF = [self.tableView convertRect:playerInTableF toView:self.tableView.superview];
        CGFloat playerInViewCenterY = playerInViewF.origin.y + playerInViewF.size.height*0.5;
        
        if((playerInViewCenterY - screenInViewCenterY) < minDiff){
            minDiff = screenInViewCenterY - playerInViewCenterY;
            playCell = cell;
        }
    }
    self.playIndexPath = [self.tableView indexPathForCell:playCell];
    return minDiff;
}

#pragma mark - 切换索引时 播放某一个 和 停止某一个

/** 
 播放某一个
 */
-(void)playWithIndexPath:(NSIndexPath *)indexPath{
    //启动或者继续播放下一个
    dispatch_async(dispatch_get_main_queue(), ^{
        if (indexPath.row < self.dataM.count) {
            TLScrollPlayModel *playModel = self.dataM[indexPath.row];
            if (playModel.player.state == TLPlayerStatePause) {
                [playModel.player play];
            }
            else{
                if (playModel.player.state != TLPlayerStateLoading) {
                    [playModel.player resume];
                }
            }
        }
    });
}

/**
 停止播放某一个
 */
-(void)stopPlayWithIndexPath:(NSIndexPath *)indexPath{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (indexPath.row < self.dataM.count) {
            TLScrollPlayModel *playModel = self.dataM[indexPath.row];
            if (playModel.player.state == TLPlayerStatePlaying) {
                [playModel.player pause];
            }
            else{
                [playModel.player stop];
            }
        }
    });
}

/**
 离开当前页面的时候停止当前页面的所有的播放
 */
-(void)stopAllPlay{
    for (TLScrollPlayModel *playModel in self.dataM) {
        if (playModel.player.state == TLPlayerStatePlaying) {
            [playModel.player pause];
        }
        else{
            [playModel.player stop];
        }
    }
}

/**
 获取索引对应的cell
 */
-(TLScrollPlayCell *)getIndextCell:(NSIndexPath *)indexPath{
    TLScrollPlayCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)dealloc{
    for (TLScrollPlayModel *model in self.dataM) {
        [model.player destroy];
    }
    NSLog(@"---%s",__func__);
}

@end
